<!--
	作者：offline
	时间：2018-11-28
	描述：送货单详情/创建
-->

<template>
	<div class="m-view-deliverComponents m-window">
		<el-row :gutter="5">
			<el-col :span="24">
				<el-row :gutter="10">
					<el-col :span="2" v-if="btnShow&&accountType!=1&&!notTransport" class="m-floatRight">
						<el-button type="primary" @click="audit" :disabled="btnDis">审核</el-button>
					</el-col>
					<el-col :span="2" v-if="btnShow&&accountType!=1&&!notTransport" class="m-floatRight">
						<el-button type="primary" @click="save" :disabled="btnDis">保存</el-button>
					</el-col>
					<el-col :span="2" v-if="dropButShow&&accountType!=1&&!notTransport" class="m-floatRight">
						<el-button type="primary" @click="dropSave" :disabled="btnDis">弃审</el-button>
					</el-col>
					<el-col :span="2" class="m-floatRight" v-if="pageLayOut=='add'&&!isTransport">
						<el-dropdown trigger="click" placement="bottom" @command="handleCommand">
							<el-button type="primary">
								选单
								<i class="el-icon-arrow-down el-icon--right"></i>
							</el-button>
							<el-dropdown-menu slot="dropdown" class="dropMenu">
								<el-dropdown-item command="1">按采购订单</el-dropdown-item>
								<el-dropdown-item command="2" v-if="false">按送货计划单</el-dropdown-item>
							</el-dropdown-menu>
						</el-dropdown>
					</el-col>
					<el-col :span="2" class="m-floatRight" v-if="pageLayOut=='add'&&isTransport">
						<el-button type="primary" @click="handleCommand('2')">选单</el-button>
					</el-col>
					<el-col :span="2" class="m-floatRight">
						<el-button @click="cancel(true)" :disabled="btnDis">返回</el-button>
					</el-col>
				</el-row>
			</el-col>
		</el-row>

		<el-form
			:model="ruleForm"
			ref="ruleForm"
			label-width="70px"
			:inline-message="true"
			label-position="left"
		>
			<el-row :gutter="5">
				<el-col :span="6">
					<el-form-item label="送货单号" prop="deliveryNo" class="rightItem">
						<el-input v-model="ruleForm.deliveryNo" placeholder="送货单号" :disabled="inputDis"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="供应商" class="rightItem">
						<el-input v-model="ruleForm.supplierName" placeholder="供应商" :disabled="inputDis"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="5">
					<el-form-item label="送货日期">
						<el-date-picker
							v-model="ruleForm.deliveryDate"
							type="date"
							placeholder="送货日期"
							value-format="yyyy-MM-dd"
							:disabled="remarkDis"
							:picker-options="pickerOptions"
						></el-date-picker>
					</el-form-item>
				</el-col>
				<el-col :span="5">
					<el-form-item label="业务类型" class="rightItem">
						<el-select value-key="id" v-model="ruleForm.busType" placeholder="业务类型" :disabled="inputDis">
							<el-option v-for="item in busOptions" :key="item.id" :label="item.label" :value="item.value"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="5">
				<el-col :span="6">
					<el-form-item label="客户" class="rightItem">
						<el-select
							value-key="id"
							v-model="ruleForm.companyCode"
							placeholder="客户名称"
							ref="content"
							:disabled="inputDis"
							filterable
						>
							<el-option
								v-for="item in comOptions"
								:key="item.id"
								:label="item.companyName"
								:value="item.companyCode"
							></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="13">
					<el-form-item label="地址" class="rightItem">
						<el-input
							v-model="ruleForm.address"
							placeholder="请输入地址"
							:disabled="remarkDis||accountType==1"
							maxlength="100"
							clearable
						></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="5">
					<el-form-item label="计划到货" class>
						<el-date-picker
							v-model="ruleForm.planDate"
							type="date"
							placeholder="计划到货日期"
							value-format="yyyy-MM-dd"
							:disabled="remarkDis"
							:picker-options="pickerOptions"
						></el-date-picker>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="5" v-if="false">
				<el-col :span="6">
					<el-form-item label="区域" class="rightItem">
						<el-input
							v-model="ruleForm.area"
							placeholder="请输入送货区域"
							:disabled="remarkDis||accountType==1"
							clearable
							maxlength="50"
						></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="6" v-if="ruleForm.transportMode==1">
					<el-form-item label="车牌" class="rightItem">
						<el-input
							v-model="ruleForm.carNum"
							placeholder="请输入车牌号"
							:disabled="remarkDis||accountType==1"
							maxlength="8"
							clearable
						></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="6" v-if="ruleForm.transportMode==3">
					<el-form-item label="车皮号" class="rightItem">
						<el-input
							v-model="ruleForm.wagonNum"
							placeholder="车皮号"
							maxlength="7"
							:disabled="remarkDis||accountType==1"
							clearable
						></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="6" v-if="ruleForm.transportMode==2">
					<el-form-item label="柜号" class="rightItem">
						<el-input
							v-model="ruleForm.containerNum"
							placeholder="请输入柜号"
							maxlength="11"
							:disabled="remarkDis||accountType==1"
							clearable
						></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="7">
					<el-form-item label="运输方式" prop="transportMode ">
						<el-select v-model="ruleForm.transportMode" :disabled="remarkDis||accountType==1">
							<el-option
								v-for="option in [
                                    { value: 1, label: '汽车' },
                                    { value: 2, label: '集装箱' },
                                    { value: 3, label: '铁路' }
                                    ]"
								:key="option.value"
								:label="option.label"
								:value="option.value"
							></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="5">
					<el-form-item label="预约卸货" class="rightItem">
						<el-select v-model="ruleForm.appointFlag" disabled>
							<el-option
								v-for="option in [{label:'是',value:1},{label:'否',value:0}]"
								:key="option.value"
								:value="option.value"
								:label="option.label"
							></el-option>
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="5">
				<el-col :span="6" v-if="isTransport||ruleForm.transportID">
					<el-form-item label="运输方" class="rightItem">
						<el-input v-model="ruleForm.transportName" placeholder="运输方" :disabled="true"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="车牌" class="rightItem">
						<el-input
							v-model="ruleForm.carNum"
							placeholder="请输入车牌号"
							:disabled="remarkDis||accountType==1"
							maxlength="8"
							clearable
						></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="isTransport||ruleForm.transportID?12:18">
					<el-form-item label="备注" class="rightItem">
						<el-input
							v-model="ruleForm.remark"
							placeholder="备注(100字)"
							:disabled="remarkDis||accountType==1"
							maxlength="100"
							clearable
						></el-input>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<div class="m-mainContent m-top2" v-loading="btnDis">
			<agGridComponents
				ref="agGirdComponent"
				:isColFit="true"
				:getGridOptions="gridOptions"
				:getColumnDefs="columnDefs"
			></agGridComponents>
		</div>
		<div class="m-page">
			<el-row :gutter="5">
				<el-form
					:model="ruleFormBottom"
					ref="ruleForm"
					label-width="70px"
					:inline-message="true"
					label-position="left"
				>
					<el-col :span="4">
						<el-form-item label="制单人">
							<el-input v-model="ruleFormBottom.creator" placeholder="制单人" disabled clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="制单日期">
							<el-date-picker
								v-model="ruleFormBottom.createDate"
								type="date"
								placeholder="送货日期"
								:picker-options="pickerOptions"
								value-format="yyyy-MM-dd"
								disabled
							></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="4">
						<el-form-item label="审核人">
							<el-input v-model="ruleFormBottom.auditor" placeholder="审核人" disabled clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="审核日期">
							<el-date-picker
								v-model="ruleFormBottom.auditDate"
								type="date"
								placeholder="审核日期"
								:picker-options="pickerOptions"
								value-format="yyyy-MM-dd"
								disabled
							></el-date-picker>
						</el-form-item>
					</el-col>
				</el-form>
			</el-row>
		</div>
		<!-- 已扫码数量弹窗 -->
		<el-dialog
			title="条码信息"
			v-if="barCodeDialogVisible"
			:visible.sync="barCodeDialogVisible"
			width="60%"
			:before-close="barCodeClose"
			v-dialogDrag
			:close-on-click-modal="false"
			:close-on-press-escape="false"
			:inline-message="true"
		>
			<div>
				<el-row :gutter="10" class="m-condition">
					<el-col :span="10">
						<el-input
							v-model="barCode"
							placeholder="请输入条码信息并按回车键进行查询"
							clearable
							@clear="onFilterChanged(barCode)"
							@keyup.enter.native="onFilterChanged(barCode)"
						></el-input>
					</el-col>
					<el-col :span="2">
						<el-button type="primary" @click="onFilterChanged(barCode)">查询</el-button>
					</el-col>
				</el-row>
			</div>
			<div class="m-agTableModel">
				<agGridComponents
					ref="barCodeGridComponent"
					:getGridOptions="barCodeGridOptions"
					:getColumnDefs="barCodeColumnDefs"
				></agGridComponents>
			</div>
			<div slot="footer" class="dialog-footer">
				<!-- <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @prev-click="handlePrevClick"
          @next-click="handleNextClick"
          :current-page="barcodePage.current"
          :page-sizes="[100,150,200,300,500]"
          :page-size="barcodePage.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="barcodePage.total"
          :pager-count="5"
				></el-pagination>-->
			</div>
		</el-dialog>
		<book-dialog
			:showBookTimeDialog="showBookTimeDialog"
			:closeBook="closeBook"
			:ruleForm="ruleForm"
			:comOptions="comOptions"
			:rowData="rowData"
			@getBookTimeForm="getBookTimeForm"
		></book-dialog>
	</div>
</template>

<script>
// import localeText from "@/i18n/agGridText";
import agGridComponents from "@/components/agGridComponents.js";
import authInfo from "@/public/authInfo.js";
import Vue from "vue";
import waterfall from "async-es/waterfall";
import _Api from "@/api";
import addOperation from "@/public/addOperation.js";
// import integerComponent from "@/components/integerComponents.js";
import NumericEditorComponent from "@/components/NumericEditorComponent.js";
import serverTime from "@/public/serverTime.js";
import constant from "@/public/constant";
import Msg from "@/public/message.js";
import buttonLink from "@/components/buttonLink.js";
import fileStream from "@/public/fileStream.js";
import { startPrint } from 'lesso-common/webprint';
import apienv from '@/api/env';
import aes from '@/public/aes';
import bookDialog from './common/bookTimeDialog'
import _utils from '@/public/utils'
const ENV = apienv[constant.appenv]
// 不包括新能源车
const PLATE_CAR_NUM = /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/;

const operator = Vue.extend({
	template: `<span>
		<el-button type="text" @click="delDetails" class="rendererClass" size="mini" v-if=" delDetailsShow && params.node.data.id >=0 ? true :false ">删除</el-button>
		</span>`,
	data () {
		return {
			delDetailsShow: operator.delDetailsShow
		};
	},
	methods: {
		delDetails () {
			this.params.context.componentParent.deleteDetails(this.params.node);
		}
	}
});

export default {
	data () {
		return {
			btnDis: false,
			inputDis: false,
			inputDis2: false,
			deliveryNo: "",
			supplierName: "",
			sendDate: "",
			busType: "",
			busOptions: [
				{ label: "普通销售", value: 1 },
				{ label: "销售退货", value: 2 }
			],
			selCompanyCode: "",
			comOptions: [],
			address: "",
			arrivalDate: "",
			remark: "",
			remarkDis: false,
			gridOptions: "",
			columnDefs: "",
			totalPlanAmount: 0,
			creator: "",
			createDate: "",
			pickerOptions: {
				disabledDate (time) {
					return time.getTime() < Date.now() - 3600 * 1000 * 24;
				}
			},
			auditor: "",
			auditDate: "",
			ruleForm: {
				address: '',
				area: '',
				carNum: '',
				appointFlag: 0,			//是否预约卸货
				containerNum: '',		//柜号
				wagonNum: '',			//车皮号
				transportID: '',			//运输方id
				transportName: '',         //运输方名称
				transportMode: 1          //运输方式
			},
			ruleFormBottom: {},
			rowData: [],
			btnShow: true,
			dropButShow: false,
			isHide: false,
			// offset: 18
			offset: 18,
			barCodeGridOptions: [],
			barCodeColumnDefs: '',
			barCodeDialogVisible: false,
			barcodePage: {
				size: 100,
				current: 1,
				total: 0
			},
			barCode: '',
			barRows: [],
			accountType: this.$global.user.userTypeId,
			// 显示预约弹窗
			showBookTimeDialog: false,
			// 预约信息
			appointmentEntity: {},
			// 是否是运输方
			isTransport: this.$global.isTransport,
			// 是否显示操作按钮
			notTransport: false
		};
	},
	methods: {
		// 验证车牌
		validTransport (form) {
			const { transportMode, containerNum, carNum, wagonNum } = form
			let valid = PLATE_CAR_NUM.test(carNum)
			if (transportMode == 1) {
				if (!valid && carNum) {
					return '请输入正确的车牌号码'
				}
			} else if (transportMode == 2) {
				if (!containerNum) {
					return '柜号不能为空'
				} else if (!_utils.validContainerNum(containerNum)) {
					return '请输入11位正确规则的柜号!'
				}
			} else if (transportMode == 3) {
				if (!wagonNum) {
					return '车皮号不能为空'
				} else if (!/^\d{7}$/g.test(wagonNum)) {
					return '请输入7位数字车皮号!'
				}
			}
		},
		// 点击扫码数量
		setClickValue (params) {
			// 扫码数量大于0时，展示扫码明细   
			if (params.data.scanAmount > 0) {
				this.barCodeDialogVisible = true
				let row = params.data
				this.$nextTick(_ => {
					this.getBarcode(row)
				})
			}
		},
		/* 分页组件事件开始 */
		handleSizeChange (parasm) {
			this.barcodePage.current = 1;
			this.barcodePage.pageSize = params;
			//   this.search();
		},
		handleCurrentChange (params) {
			// this.currentPage = params;
			this.barcodePage.current = params;
			//   this.search();
		},
		handlePrevClick (params) {
			this.barcodePage.current = params;
		},
		handleNextClick (params) {
			this.barcodePage.current = params;
		},
		/* 分页组件事件end */
		/* 关闭扫码数量弹窗 */
		barCodeClose (done) {
			this.barCode = ''
			done()
		},
		// 获取扫码信息
		getBarcode (row) {
			this.$refs.barCodeGridComponent.loading = true;
			const { deliveryNo, purOrdNo, purOrdMxNo, matCode } = row
			let params = {
				deliveryNo,
				purOrdNo,
				purOrdMxNo,
				matCode
			}
			_Api.getBarcodeList(params).then((res) => {
				let data = res.data
				this.$refs.barCodeGridComponent.loading = false;
				if (data.code == 1) {
					this.barRows = data.rows.splice(0)
					this.$refs.barCodeGridComponent.gridOptions.api.setRowData(this.barRows);
					// this.$refs.barCodeGridComponent.rowDataChange = true;
				} else {
					Msg.showErrorMsg(data.info)
				}
			}).catch((err) => {
				Msg.showErrorMsg(err.data.message)
			})
		},
		// 过滤条码
		onFilterChanged (barcode) {
			let filterRows = this.barRows.filter((row) => {
				return row.barcode.indexOf(barcode) > -1
			})
			this.$refs.barCodeGridComponent.gridOptions.api.setRowData(filterRows);
		},
		//获取送货单号
		getDeliveryNo () {
			var that = this;
			this.$refs.agGirdComponent.loading = true;
			_Api
				.getDeliveryNo()
				.then(function (response) {
					var data = response.data;
					if (data.code == "1") {
						// that.ruleForm.deliveryNo = data.rows;
						that.$set(that.ruleForm, "deliveryNo", data.rows);
					} else {
						Msg.showErrorMsg(data.info);
					}
					that.$refs.agGirdComponent.loading = false;
				})
				.catch(err => {
					Msg.showErrorMsg(err.data.message);
				});
		},
		//审核
		audit () {

			var that = this;
			var obj = {};
			this.$refs.agGirdComponent.gridOptions.api.stopEditing();
			let valid = this.validTransport(this.ruleForm)
			if (valid) {
				Msg.showPopMsg(valid)
				return
			}
			if (
				this.ruleForm.deliveryDate == "" ||
				this.ruleForm.deliveryDate == null
			) {
				Msg.showPopMsg("请选择送货日期");
				return;
			}
			if (this.ruleForm.planDate == null || this.ruleForm.planDate == "") {
				Msg.showPopMsg("请选择计划到货日期");
				return;
			}
			if (this.ruleForm.deliveryDate > this.ruleForm.planDate) {
				Msg.showPopMsg("送货日期不能大于计划到货日期！");
				return;
			}

			if (this.rowData.length < 1) {
				Msg.showPopMsg("明细不能为空!");
				return;
			}

			if (this.ruleForm.area == "" && this.ruleForm.appointFlag == 1) {
				Msg.showPopMsg("区域不能为空!");
				return;
			}
			// if (this.ruleForm.carNum == "" && this.ruleForm.appointFlag == 1) {
			// 	Msg.showPopMsg("车号不能为空!");
			// 	return;
			// }
			// if (!PLATE_CAR_NUM.test(this.ruleForm.carNum)) {
			// 		Msg.showPopMsg("请输入正确的车牌号");
			// 		return;
			//     }
			var reg = /^[0-9]+(.[0-9]{1,3})?$/; //有两位小数的正实数
			setTimeout(() => {
				for (let i in this.rowData) {
					//验证数字输入        
					if (!reg.test(this.rowData[i].priceAmount)) {
						Msg.showPopMsg("行号：" + this.rowData[i].deliveryIMxNo + " 的价格数量只能输入数字且不超过三位小数!!");
						return;
					}
					if (!reg.test(this.rowData[i].actualAmount)) {
						Msg.showPopMsg("行号： " + this.rowData[i].deliveryIMxNo + " 的实际送货数量只能输入数字且不超过三位小数!");
						return;
					}
					if (this.rowData[i].actualAmount <= 0) {
						Msg.showPopMsg("行号：" + this.rowData[i].deliveryIMxNo + " 物料号：" + this.rowData[i].matCode + " 的送货数量要大于0！");
						return;
					}
					if (this.rowData[i].priceAmount == null || this.rowData[i].priceAmount <= 0) {
						Msg.showPopMsg("行号：" + this.rowData[i].deliveryIMxNo + " 物料号：" + this.rowData[i].matCode + " 的价格数量要大于0！");
						return;
					}
					if (typeof (this.rowData[i].remark) == 'string' && this.rowData[i].remark.lentgh > 20) {
						Msg.showPopMsg("行号：" + this.rowData[i].deliveryIMxNo + " 物料号：" + this.rowData[i].matCode + " 的备注不能超过20个字符！");
						return;
					}
					//若是扫码明细，审核时送货数量要等于已扫码数量 jjc20190324 begin
					if (this.rowData[i].isBarCode == 1 && this.rowData[i].actualAmount != this.rowData[i].scanAmount) {
						Msg.showPopMsg("行号：" + this.rowData[i].deliveryIMxNo + " 物料号：" + this.rowData[i].matCode + " 的送货数量与已扫码数量不一致！");
						return;
					}
					//jjc20190324 end
					if (!this.checkRange(this.rowData[i])) {
						Msg.showPopMsg("行号：" + this.rowData[i].deliveryIMxNo + " 物料号：" + this.rowData[i].matCode + " 的价格数量误差范围不能超过25%！");
						return;
					}
					// if (this.rowData[i].unlimited === 0) {
					//   if (this.rowData[i].actualAmount >= 0) {
					//     if (this.rowData[i].actualAmount > this.rowData[i].orderAmount) {
					//       Msg.showPopMsg(
					//         "行号：" +
					//           this.rowData[i].deliveryIMxNo +
					//           " 物料号：" +
					//           this.rowData[i].matCode +
					//           " 的送货数量不能大于订单数量！"
					//       );
					//       return;
					//     }
					//   }
					// }
				}
				//this.ruleForm.purOrdNo = this.getClickValue.purOrdNo;
				let dt = new Date();
				let orderId = ''
				if (this.pageLayOut == "add") {
					//创建人
					this.ruleForm.creator = constant.userName; //this.supplierInfo[0].supplierName;
					this.ruleForm.creatorId = constant.userId; //this.supplierInfo[0].id;
					this.ruleForm.createDate = dt.Format("yyyy-MM-dd HH:mm:ss");
					this.ruleForm.purOrdNo = this.rowData[0].purOrdNo;
					orderId = this.rowData[0].purOrdID
				} else {
					//保存时不要用ruleForm，应该新创建一个对象 后面优化
					Vue.delete(this.ruleForm, "creator");
					Vue.delete(this.ruleForm, "creatorId");
					Vue.delete(this.ruleForm, "createDate");
					orderId = this.ruleForm.orderId
				}
				for (let a in this.rowData) {
					this.rowData[a].deliveryNo = this.ruleForm.deliveryNo;
				}
				//修改人
				this.ruleForm.modifyer = constant.userName; //this.supplierInfo[0].supplierName;
				this.ruleForm.modifyerId = constant.userId; //this.supplierInfo[0].id;
				this.ruleForm.modifyDate = dt.Format("yyyy-MM-dd HH:mm:ss"); //this.supplierInfo[0].id;

				this.ruleForm.deliveryDate = new Date(this.ruleForm.deliveryDate).Format(
					"yyyy-MM-dd HH:mm:ss"
				);
				this.ruleForm.planDate = new Date(this.ruleForm.planDate).Format(
					"yyyy-MM-dd HH:mm:ss"
				);
				this.ruleForm.billState = 3;
				this.ruleForm.auditor = constant.userName;
				this.ruleForm.auditorId = constant.userId;
				this.ruleForm.auditDate = dt.Format("yyyy-MM-dd HH:mm:ss");
				this.ruleForm.supplierCode = this.supplierInfo[0].supplierCode;

				if (this.ruleForm.appointFlag == 1 && Object.keys(this.appointmentEntity).length == 0) {
					this.showBookTimeDialog = true;
					return
				}
				if (this.ruleForm.appointFlag == 1 && Object.keys(this.appointmentEntity).length > 0) {
					obj.appointmentEntity = this.appointmentEntity
				}




				obj.tblDeliverybill = this.ruleForm;
				obj.tblDeliverymxs = this.rowData;
				//日期服务端端处理
				Vue.delete(obj.tblDeliverybill, "auditDate");
				Vue.delete(obj.tblDeliverybill, "modifyDate");
				Vue.delete(obj.tblDeliverybill, "createDate");
				that.btnDis = true;
				waterfall([
					function auditDelivery (callback) {
						if (that.deliveryState === "import") {
							_Api
								.importDeliverybill(obj)
								.then(function (response) {
									that.btnDis = false;
									var data = response.data;
									if (data.code == "1") {
										Msg.showSuccessMsg("操作成功");
										//that.ruleForm.id = data.rows.deliveryBillId;
										callback(null, data.rows.deliveryBillId);
										that.cancel(false);
									} else {
										Msg.showErrorMsg(data.info);
									}
								})
								.catch(err => {
									Msg.showErrorMsg(err.message);
									that.btnDis = false;
								});
						} else {
							that.saveDeliveryData(obj, orderId).then(data => {
								callback(null, data.rows.deliveryBillId);
								that.cancel(true);
								that.btnDis = false;
							}).catch(err => {
								Msg.showErrorMsg(err);
								that.btnDis = false;
							})
						}
					},
					function print (billId, callback) {
						if (constant.userAgent == 'web') {
							fileStream.getFileInfo('sendDelivery').then((data) => {
								startPrint({
									basicUrl: ENV['srm'], //权限接口地址
									reportUrl: `${ENV['srm']}download2?viewPath=${data.url}&groupName=${data.groupName}`,  //打印模板地址
									dataUrl: 'tblDeliverybill/deliverybillInfo', //数据接口地址
									params: {
										'token': '',
										'id': billId,
										'supplierCode': that.ruleForm.supplierCode,
										"remarkFlag": 'delivery'
									}, //参数对象
									printType: 'preview'     // 打印方式print直接打印，preview先预览
								})
							}).catch((err) => {
								that.$alert(err, {
									showClose: false,
									confirmButton: "确定",
									customClass: "alertFailure"
								});
							})
						} else {
							that.printPc(billId, that.ruleForm.supplierCode)
						}
					}
				]);
			}, 100)
		},
		// 客户端送货单打印
		printPc (billId, supplierCode) {
			const ENCRYPT_KEY = 'lesso2128token11'
			waterfall([
				(callback) => {
					_Api.getPrintToken().then(({ data }) => {
						let token = aes.encrypt(data, ENCRYPT_KEY);
						callback(null, token);
					}).catch(err => {
						Msg.showErrorMsg(err.data.message)
					})
				},
				(token, callback) => {
					_Api.getDeliveryPrintData({ id: billId, token: token, supplierCode: supplierCode }).then(({ data }) => {
						let printData = data.rows
						callback(null, printData)
					}).catch(err => {
						Msg.showErrorMsg(err.data.message)
					})
				},
				(printData, callback) => {
					if (constant.printType == 'local') {
						ipcRenderer.send("IPCR_M_PRINTLOCAL", {
							type: type,
							rows: printData,
							optype: 'pr',
							isdefaultp: 1//控制是否直接打印,0为选择打印、1为直接打印
						});
					} else {
						fileStream.getFileInfo('sendDelivery_pc', printData).then((data) => {
							ipcRenderer.send("IPCR_M_PRINT", {
								type: 'sendDelivery_pc',
								rows: printData,
								groupName: data.groupName,
								optype: "pr",
								url: data.url,
								isdefaultp: 1//控制是否直接打印,0为选择打印、1为直接打印
							})
						}).catch((err) => {
							Msg.showErrorMsg(err)
						})
					}
				}
			])
		},
		cancel: function (msg) {
			this.$emit("cancelComponents", msg);
		},
		save () {
			this.$refs.agGirdComponent.gridOptions.api.stopEditing();
			let that = this
			let valid = this.validTransport(this.ruleForm)
			if (valid) {
				Msg.showPopMsg(valid)
				return
			}
			//保存
			setTimeout(() => {
				if (that.pageLayOut == "add") {
					that.addSave();
				} else if (that.pageLayOut == "edit") {
					that.editSave();
				}
			}, 100)
		},
		//新增保存
		addSave () {
			if (this.ruleForm.address == "" || this.ruleForm.address == null) {
				Msg.showPopMsg("请输入地址");
				return;
			}
			if (
				this.ruleForm.deliveryDate == "" ||
				this.ruleForm.deliveryDate == null
			) {
				Msg.showPopMsg("请选择送货日期");
				return;
			}
			if (this.ruleForm.planDate == null || this.ruleForm.planDate == "") {
				Msg.showPopMsg("请选择计划到货日期");
				return;
			}
			if (this.ruleForm.deliveryDate > this.ruleForm.planDate) {
				Msg.showPopMsg("送货日期不能大于计划到货日期！");
				return;
			}
			var obj = {};
			var that = this;
			if (this.rowData.lentgh < 1) {
				Msg.showPopMsg("明细不能为空!");
				return;
			}
			var reg = /^[0-9]+(.[0-9]{1,3})?$/; //有两位小数的正实数
			for (let i in this.rowData) {
				//验证数字输入        
				if (!reg.test(this.rowData[i].priceAmount)) {
					Msg.showPopMsg("行号：" + this.rowData[i].deliveryIMxNo + " 的价格数量只能输入数字且不超过三位小数!!");
					return;
				}
				if (!reg.test(this.rowData[i].actualAmount)) {
					Msg.showPopMsg("行号： " + this.rowData[i].deliveryIMxNo + " 的实际送货数量只能输入数字且不超过三位小数!!");
					return;
				}
				if (this.rowData[i].actualAmount <= 0) {
					Msg.showPopMsg("行号：" + this.rowData[i].deliveryIMxNo + " 物料号：" + this.rowData[i].matCode + " 的送货数量要大于0！");
					return;
				}
				if (this.rowData[i].priceAmount == null || this.rowData[i].priceAmount <= 0) {
					Msg.showPopMsg("行号：" + this.rowData[i].deliveryIMxNo + " 物料号：" + this.rowData[i].matCode + " 的价格数量要大于0！");
					return;
				}
				if (typeof (this.rowData[i].remark) == 'string' && this.rowData[i].remark.lentgh > 20) {
					Msg.showPopMsg("行号：" + this.rowData[i].deliveryIMxNo + " 物料号：" + this.rowData[i].matCode + " 的备注不能超过20个字符！");
					return;
				}
				//若是扫码明细，保存时送货数量不能小于已扫码数量 jjc20190324 begin
				if (this.rowData[i].isBarCode == 1 && this.rowData[i].actualAmount < this.rowData[i].scanAmount) {
					Msg.showPopMsg("行号：" + this.rowData[i].deliveryIMxNo + " 物料号：" + this.rowData[i].matCode + " 的送货数量不能小于已扫码数量！");
					return;
				}
				//jjc20190324 end
				if (!this.checkRange(this.rowData[i])) {
					Msg.showPopMsg("行号：" + this.rowData[i].deliveryIMxNo + " 物料号：" + this.rowData[i].matCode + " 的价格数量误差范围不能超过25%！");
					return;
				}
			}

			this.ruleForm.billState = 1;
			this.ruleForm.deliveryDate = new Date(this.ruleForm.deliveryDate).Format(
				"yyyy-MM-dd HH:mm:ss"
			);
			this.ruleForm.planDate = new Date(this.ruleForm.planDate).Format(
				"yyyy-MM-dd HH:mm:ss"
			);
			this.ruleForm.creator = constant.userName;
			this.ruleForm.creatorId = constant.userId;
			this.ruleForm.supplierCode = this.supplierInfo[0].supplierCode;
			this.ruleForm.purOrdNo = this.rowData[0].purOrdNo;
			for (let a in this.rowData) {
				this.rowData[a].deliveryNo = this.ruleForm.deliveryNo;
				//jjc20190216 只要有一条记录实发数大于0都是拣配中
				if (this.rowData[a].actualAmount > 0) this.ruleForm.billState = 2;
			}
			//   if(this.ruleForm.auditDate != null)
			//   	this.ruleForm.auditDate =  new Date(this.ruleForm.auditDate).Format("yyyy-MM-dd HH:mm:ss"); //jjc20190216

			obj.tblDeliverybill = this.ruleForm;
			obj.tblDeliverymxs = this.rowData;

			//日期服务端端处理
			Vue.delete(obj.tblDeliverybill, "auditDate");
			Vue.delete(obj.tblDeliverybill, "modifyDate");
			Vue.delete(obj.tblDeliverybill, "createDate");
			this.btnDis = true;
			if (this.deliveryState === 'import') {
				_Api
					.importDeliverybill(obj)
					.then(function (response) {
						var data = response.data;
						if (data.code == "1") {
							Msg.showSuccessMsg("操作成功");
							that.cancel(false);
						} else {
							Msg.showErrorMsg(data.info);
						}
						that.btnDis = false;
					})
					.catch(err => {
						Msg.showErrorMsg(err.data.message);
						that.btnDis = false;
					});
			} else {
				this.saveDeliveryData(obj, obj.tblDeliverymxs[0].purOrdID).then(data => {
					this.cancel(true);
					this.btnDis = false;
				}).catch(err => {
					Msg.showErrorMsg(err);
					this.btnDis = false;
				})
			}
		},
		// 校验价格单位误差
		checkRange (data) {
			let range = true;
			if (data) {
				const { priceAmount, actualAmount, numerator, denominator } = data
				let newAmount = actualAmount * (numerator / denominator)
				let minAmount = newAmount - newAmount * 0.25
				let maxAmount = newAmount + newAmount * 0.25
				if (Number(priceAmount) > maxAmount || Number(priceAmount) < minAmount) {
					range = false
				}
				return range
			}
		},
		//修改保存
		editSave () {
			var obj = {};
			// this.$refs.agGirdComponent.gridOptions.api.stopEditing();
			if (this.ruleForm.address == "" || this.ruleForm.address == null) {
				Msg.showPopMsg("请输入地址");
				return;
			}
			if (
				this.ruleForm.deliveryDate == "" ||
				this.ruleForm.deliveryDate == null
			) {
				Msg.showPopMsg("请选择计划到货日期");
				return;
			}
			if (this.ruleForm.planDate == "" || this.ruleForm.planDate == null) {
				Msg.showPopMsg("请选择送货日期");
				return;
			}
			if (this.ruleForm.deliveryDate > this.ruleForm.planDate) {
				Msg.showPopMsg("计划送货日期不能大于送货日期！");
				return;
			}
			if (this.rowData.lentgh < 1) {
				Msg.showPopMsg("明细不能为空!");
				return;
			}

			var reg = /^[0-9]+(.[0-9]{1,3})?$/; //有两位小数的正实数
			for (let i in this.rowData) {
				//验证数字输入        
				if (!reg.test(this.rowData[i].priceAmount)) {
					Msg.showPopMsg("行号：" + this.rowData[i].deliveryIMxNo + " 的价格数量只能输入数字且不超过三位小数!!");
					return;
				}
				if (!reg.test(this.rowData[i].actualAmount)) {
					Msg.showPopMsg("行号： " + this.rowData[i].deliveryIMxNo + " 的实际送货数量只能输入数字且不超过三位小数!");
					return;
				}
				if (this.rowData[i].actualAmount <= 0) {
					Msg.showPopMsg("行号：" + this.rowData[i].deliveryIMxNo + " 物料号：" + this.rowData[i].matCode + " 的送货数量要大于0！");
					return;
				}
				if (this.rowData[i].priceAmount == null || this.rowData[i].priceAmount <= 0) {
					Msg.showPopMsg("行号：" + this.rowData[i].deliveryIMxNo + " 物料号：" + this.rowData[i].matCode + " 的价格数量要大于0！");
					return;
				}
				if (this.rowData[i].remark.length > 20) {
					Msg.showPopMsg("行号：" + this.rowData[i].deliveryIMxNo + " 物料号：" + this.rowData[i].matCode + " 的备注不能超过20个字符！");
					return;
				}
				//若是扫码明细，保存时送货数量不能小于已扫码数量 jjc20190324 begin
				if (this.rowData[i].isBarCode == 1 && this.rowData[i].actualAmount < this.rowData[i].scanAmount) {
					Msg.showPopMsg("行号：" + this.rowData[i].deliveryIMxNo + " 物料号：" + this.rowData[i].matCode + " 的送货数量不能小于已扫码数量！");
					return;
				}
				//jjc20190324 end
				if (!this.checkRange(this.rowData[i])) {
					Msg.showPopMsg("行号：" + this.rowData[i].deliveryIMxNo + " 物料号：" + this.rowData[i].matCode + " 的价格数量误差范围不能超过25%！");
					return;
				}
				// if (this.rowData[i].unlimited === 0) {
				//   if (this.rowData[i].actualAmount >= 0) {
				//     if (this.rowData[i].actualAmount > this.rowData[i].orderAmount) {
				//       Msg.showPopMsg(
				//         "行号：" +
				//           this.rowData[i].deliveryIMxNo +
				//           " 物料号：" +
				//           this.rowData[i].matCode +
				//           " 的送货数量不能大于订单数量！"
				//       );
				//       return;
				//     }
				//   }
				// }
			}
			//赋值
			//this.ruleForm.purOrdNo = this.getClickValue.purOrdNo;
			this.ruleForm.modifyer = constant.userName; //this.supplierInfo[0].supplierName;
			this.ruleForm.modifyerId = constant.userId; //this.supplierInfo[0].id;
			//this.ruleForm.modifyDate = new Date().Format("yyyy-MM-dd HH:mm:ss"); //this.supplierInfo[0].id;
			this.ruleForm.deliveryDate = new Date(this.ruleForm.deliveryDate).Format(
				"yyyy-MM-dd HH:mm:ss"
			);
			this.ruleForm.planDate = new Date(this.ruleForm.planDate).Format(
				"yyyy-MM-dd HH:mm:ss"
			);
			//   if(this.ruleForm.auditDate != null)
			//   	this.ruleForm.auditDate =  new Date(this.ruleForm.auditDate).Format("yyyy-MM-dd HH:mm:ss"); //jjc20190216
			this.ruleForm.purOrdNo = this.rowData[0].purOrdNo;
			this.ruleForm.billState = 1;

			for (let a in this.rowData) {
				this.rowData[a].creator = this.ruleForm.creator; //jjc
				this.rowData[a].deliveryNo = this.ruleForm.deliveryNo;
				//jjc20190216 只要有一条记录实发数大于0都是拣配中
				if (this.rowData[a].actualAmount > 0) {
					this.ruleForm.billState = 2;
					break;
				}
			}
			obj.tblDeliverybill = this.ruleForm;
			obj.tblDeliverymxs = this.rowData;
			//日期服务端端处理
			Vue.delete(obj.tblDeliverybill, "auditDate");
			Vue.delete(obj.tblDeliverybill, "modifyDate");
			Vue.delete(obj.tblDeliverybill, "createDate");

			this.btnDis = true;
			this.saveDeliveryData(obj, this.ruleForm.orderId).then(data => {
				this.cancel(true);
				this.btnDis = false;
			}).catch(err => {
				Msg.showErrorMsg(err);
				this.btnDis = false;
			})
		},

		//创建底部合计行
		createBottomRow (count, prefix) {
			var result = [
				{
					matName: "合计",
					actualAmount: this.totalPlanAmount,
					scanAmount: ''
				}
			];
			return result;
		},
		// 保存送货单
		saveDeliveryData (obj, orderId) {
			return new Promise((resolve, reject) => {
				_Api.saveDelivery(obj).then((response) => {
					let data = response.data;
					if (data.code == "1") {
						Msg.showSuccessMsg("操作成功");
						resolve(data)
					} else {
						this.btnDis = false;
						let order = {}
						if (data.info == 1) {
							Msg.showPopMsg('订单已被退回或被强制收回,暂不能做后续操作!')
						} else if (data.info == 2) {
							order = {
								orderId: orderId,
								ordStatus: 4
							}
							this.viewOrderDetail('订单未确认或已变更,请先确认订单!', order)
						} else {
							reject(data.info)
						}
					}
				})
					.catch(err => {
						reject(err.data.message)
					})
			})
		},
		// 跳转订单详情
		viewOrderDetail (msg, order) {
			this.$confirm(msg, '提示', {
				confirmButtonText: '查看订单',
				cancelButtonText: '确定',
				type: 'warning'
			}).then(() => {
				this.$emit('viewOrder', order)
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消删除'
				});
			});
		},
		//获取并展示送货单内容
		displayDeliverybillDetail (deliveryBillId) {
			var obj = {
				deliveryBillId: deliveryBillId
			};
			var that = this;
			this.$refs.agGirdComponent.loading = true;
			_Api
				.getDeliverybillDetail(obj)
				.then(function (response) {
					var data = response.data;
					if (data.code == "1") {
						//处理表头  这里赋值日期控件不能清空内容  先注释 jjc20190224
						// that.ruleForm.auditDate = data.rows.auditDate;
						// that.ruleForm.auditor = data.rows.auditor;
						// that.ruleForm.billState = data.rows.billState;
						// that.ruleForm.companyCode = data.rows.companyCode;
						// that.ruleForm.companyName = data.rows.companyName;
						// that.ruleForm.createDate = data.rows.createDate;
						// that.ruleForm.creator = data.rows.creator;
						//that.ruleForm.deliveryDate = data.rows.deliveryDate; 
						// that.ruleForm.deliveryNo = data.rows.deliveryNo;
						// that.ruleForm.planDate = data.rows.planDate;
						// that.ruleForm.purOrdNoMain = data.rows.purOrdNoMain;
						// that.ruleForm.remark = data.rows.remark; //后端没返回jjc20190224 
						// that.ruleForm.supplierCode = data.rows.supplierCode;
						// that.ruleForm.supplierName = data.rows.supplierName;   
						// that.ruleForm.id = deliveryBillId;
						// that.ruleForm.busType = 1;  //后端没返回jjc20190224  
						// //that.ruleForm.address = data.rows.address;  //后端没返回jjc20190224     

						// if (that.ruleForm.billState === 1 || that.ruleForm.billState === 2)
						//   that.btnShow = true;
						// else 
						//   that.btnShow = false;

						// if (that.ruleForm.billState === 3) {
						//   that.remarkDis = true;
						//   that.offset = 22;
						//   that.$refs.agGirdComponent.gridOptions.columnApi.setColumnVisible(
						//     "operator",
						//     false
						//   );
						// } 
						// else 
						//   that.remarkDis = false;
						//处理明细
						if (data.total > 0) {
							//
							// that.$refs.agGirdComponent.gridOptions.api.setRowData(data.rows.tblDeliverymxs.splice(0));
							that.$set(that.ruleForm, 'area', data.rows.area)
							//   that.ruleForm.area = data.rows.area
							that.$set(that.ruleForm, 'appointFlag', data.rows.appointFlag)
							that.$set(that.ruleForm, 'transportMode', data.rows.transportMode || 1)
							that.$set(that.ruleForm, 'containerNum', data.rows.containerNum)
							that.$set(that.ruleForm, 'wagonNum', data.rows.wagonNum)
							that.ruleForm.transportID = data.rows.transportID
							that.ruleForm.transportName = data.rows.transportName
							if (!that.isTransport && data.rows.transportID) that.notTransport = true
							if (!that.ruleForm.planDate) {
								that.$set(that.ruleForm, 'planDate', data.rows.planDate)
							}
							if (!that.ruleForm.remark) {
								that.$set(that.ruleForm, 'remark', data.rows.remark)
							}
							if (!that.ruleForm.carNum) {
								that.$set(that.ruleForm, 'carNum', data.rows.carNum)
							}
							if (!that.ruleForm.orderId) {
								that.$set(that.ruleForm, 'orderId', data.rows.orderId)
							}
							that.rowData = data.rows.tblDeliverymxs.splice(0);
							let hideCol = that.rowData.every(row => {
								// 判断明细中所有价格单位与单位是否一致
								return row.unitCode == row.priceUnit
							})
							if (hideCol) {
								that.$refs.agGirdComponent.gridOptions.columnApi.setColumnVisible(
									"priceUnit",
									false
								);
								that.$refs.agGirdComponent.gridOptions.columnApi.setColumnVisible(
									"priceAmount",
									false
								);
							}
							if (!that.rowData[0].planNo) {
								that.$refs.agGirdComponent.gridOptions.columnApi.setColumnVisible(
									"planNo",
									false
								);
								that.$refs.agGirdComponent.gridOptions.columnApi.setColumnVisible(
									"planMxNo",
									false
								);
							}
							that.$refs.agGirdComponent.gridOptions.api.setRowData(that.rowData);
							that.ruleFormBottom = data.rows;
							that.totalPlanAmount = 0;
							that.$refs.agGirdComponent.gridOptions.api.forEachNode(function (node) {
								that.totalPlanAmount = addOperation.accAdd(
									node.data.actualAmount,
									that.totalPlanAmount
								);
								that.$refs.agGirdComponent.gridOptions.api.setPinnedBottomRowData(
									that.createBottomRow(1, "Bottom")
								);
							});
							that.$refs.agGirdComponent.rowDataChange = true;
							if (that.getClickValue.billState > 2 && that.pageLayOut == "edit") {
								var col = that.$refs.agGirdComponent.gridOptions.columnApi.getAllDisplayedColumns();
								for (var c in col) {

									col[c].colDef.editable = () => {
										return false;
									};
								}
							}
							//							let allColumnIds = [];
							//							that.$refs.agGirdComponent.gridOptions.columnApi.getAllColumns().forEach(function(column) {
							//								allColumnIds.push(column.colId);
							//							});
							//							that.$refs.agGirdComponent.gridOptions.columnApi.autoSizeColumns(allColumnIds);
						} else {
							that.$refs.agGirdComponent.gridOptions.api.setRowData([]);
						}
						that.$refs.agGirdComponent.loading = false;
					} else {
						Msg.showErrorMsg(data.info);
						that.$refs.agGirdComponent.loading = false;
					}
				})
				.catch(err => {
					Msg.showErrorMsg(err.data.message);
					that.btnDis = false;
				});
		},
		//删除明细行
		deleteDetails (params) {
			var that = this;
			if (params.data.id > 0 && params.data.id != null) {
				let sumId = 0;
				this.$refs.agGirdComponent.gridOptions.api.forEachNode(function (node) {
					if (node.data.id > 0) sumId++;
				});
				if (sumId == 1) {
					Msg.showErrorMsg("至少保留1条已保存的数据！");
					return;
				}
				this.$confirm("是否确认删除该数据？", "消息提示", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					distinguishCancelAndClose: true
				})
					.then(() => {
						if (params.data.id > 0) {
							var obj = {
								id: params.data.id,
								delFlag: 1,
								modifyer: this.$global.user.employeeName,
								modifyerId: this.$global.user.id
							};
							_Api
								.deleteDeliveryDetail(obj)
								.then(function (response) {
									var data = response.data;
									if (data.code == "1") {
										Msg.showSuccessMsg("操作成功");
										that.afterDel(params);
									} else {
										Msg.showErrorMsg(data.info);
									}
								})
								.catch(err => {
									Msg.showErrorMsg(err.message);
									that.btnDis = false;
								});
						}
					})
					.catch(() => { });
			} else {
				let sumId = 0;
				this.$refs.agGirdComponent.gridOptions.api.forEachNode(function (node) {
					if (node.data.id == 0) sumId++;
				})
				if (sumId == 1) {
					Msg.showErrorMsg("至少保留1条已保存的数据！");
					return;
				}
				this.$confirm("是否确认删除该数据？", "消息提示", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					distinguishCancelAndClose: true
				})
					.then(function (response) {
						that.afterDel(params);
					})
					.catch(() => { });
			}
		},
		//删除明细后重算合计行
		afterDel (params) {
			var arr = [];
			var that = this;
			arr.push(params.data);
			//删除表格行
			this.$refs.agGirdComponent.gridOptions.api.updateRowData({
				remove: arr
			});
			this.rowData.splice(params.rowIndex, 1);
			//重算合计行
			this.totalPlanAmount = 0;
			this.$refs.agGirdComponent.gridOptions.api.forEachNode(function (node) {
				if (node.data.actualAmount != null) {
					that.totalPlanAmount = addOperation.accAdd(
						node.data.actualAmount,
						that.totalPlanAmount
					);
					that.$refs.agGirdComponent.gridOptions.api.setPinnedBottomRowData(
						that.createBottomRow(1, "Bottom")
					);
				}
			});
		},
		cellFocused (params) {
			let that = this;
			if (params.column) {
				// 判断送货单是否是按计划单创建
				// let isPlan;
				// for (let i in this.rowData) {
				// 	if (this.rowData[i].planNo && this.rowData[i].planNo !== '') {
				// 		isPlan = true
				// 		break
				// 	} else {
				// 		isPlan = false
				// 		break
				// 	}
				// }
				this.$refs.agGirdComponent.gridOptions.api.forEachNode(function (node) {
					let col = node.columnApi.getAllDisplayedColumns();
					// 如果是按计划单创建送货数量不可编辑
					// if (isPlan) {
					// 	for (let c in col) {
					// 		if (col[c].colId == "actualAmount") {
					// 			col[c].colDef.editable = () => {
					// 				return false;
					// 			};
					// 		}
					// 	}
					// }
					if (that.pageLayOut == "edit" && that.getClickValue.billState > 2) {
						for (let c in col)
							col[c].colDef.editable = () => {
								return false;
							};
					} else {
						//jjc20190324 begin
						// for (let c in col) {
						//   if (col[c].colId == "actualAmount") {

						//     col[c].colDef.editable = function(node) {
						//       if (node.data.isBarCode === 0) return true;
						//       else return false;
						//     };
						//   }
						// }
						//jjc20190324 end
					}
				});
			}
		},
		// 单元格值change事件
		cellValueChanged (pra) {
			var that = this;
			this.totalPlanAmount = 0;
			// 送货数量改变计算默认价格数量
			const { actualAmount, denominator, numerator } = pra.node.data
			let rowIndex = pra.node; // that.$refs.agGirdComponent.gridOptions.api.getRowNode(pra.node.rowIndex);
			let priceAmount = actualAmount * (numerator / denominator)
			let price = priceAmount.toString().split('.')
			if (price.length > 1) {
				rowIndex.setDataValue("priceAmount", priceAmount.toFixed(3));
			} else {
				rowIndex.setDataValue("priceAmount", priceAmount);
			}
			this.$refs.agGirdComponent.gridOptions.api.forEachNode(function (node) {
				// let col = node.columnApi.getAllDisplayedColumns();
				if (
					node.data.actualAmount == 0 ||
					node.data.actualAmount > 0 ||
					node.data.actualAmount < 0
				) {
					that.totalPlanAmount = addOperation.accAdd(
						node.data.actualAmount,
						that.totalPlanAmount
					);
					that.$refs.agGirdComponent.gridOptions.api.setPinnedBottomRowData(
						that.createBottomRow(1, "Bottom")
					);
				}
			});
		},
		cellEditingStarted (params) {
			if (params.rowPinned) params.api.stopEditing();
		},

		//弃审功能
		dropSave () {
			var that = this;
			var obj = {
				"tblDeliverybill": {
					"id": this.ruleForm.id,
					"deliveryNo": this.ruleForm.deliveryNo,
					"purOrdNo": this.ruleForm.purOrdNo,
					"modifyer": constant.userName,
					"modifyerId": constant.userId
				},
				"tblDeliverymxs": this.rowData
			};
			that.btnDis = true;
			_Api
				.abandonDelivery(obj)
				.then(function (response) {
					var data = response.data;
					if (data.code == "1") {
						Msg.showSuccessMsg("弃审操作成功");
						that.cancel(true);
					} else {
						Msg.showErrorMsg(data.info);
					}
					that.btnDis = false;
				})
				.catch(err => {
					Msg.showErrorMsg(err.message);
					that.btnDis = false;
				});
		},
		girdReady (that) {
			let column = that.$refs.agGirdComponent.gridOptions.columnApi.getAllDisplayedColumns()
			let isPlan = that.rowData.some((row) => {
				return row.planNo && row.planNo != ''
			})
			column.forEach((col) => {
				if (!isPlan) {
					if (that.getClickValue.billState < 3 && that.pageLayOut == "edit" && col.colDef.editable || that.pageLayOut == "add" && col.colDef.editable) {
						col.colDef.cellStyle = () => {
							return { 'background-color': '#fff' };
						};
					} else {
						col.colDef.cellStyle = () => {
							return null
						};
					}
				} else {
					if (col.colDef.editable && col.colId !== "actualAmount") {
						col.colDef.cellStyle = () => {
							return { 'background-color': '#fff' };
						}
					} else {
						col.colDef.cellStyle = () => {
							return null
						}
					}
				}
			})
		},
		// 选择下拉项回调
		handleCommand (command) {
			switch (command) {
				case "1":
					this.$emit('selectBill', 'order')
					break;
				case "2":
					this.$emit('selectBill', 'plan')
					break
			}
		},
		// 确认添加订单到送货单
		createdDelivery (rowData, companyInfo) {
			this.ruleForm.companyId = companyInfo.id;
			this.ruleForm.companyCode = companyInfo.companyCode;
			this.ruleForm.address = rowData[0].address;
			this.ruleForm.busType = 1;
			if (this.$global.user.userTypeId == 1) {
				this.ruleForm.supplierId = this.supplierInfo[0].id;
				this.ruleForm.supplierCode = this.supplierInfo[0].supplierCode;
				this.ruleForm.supplierName = this.supplierInfo[0].supplierName;
			}
			//设置送货日期    
			if (!rowData[0].sendDate) {
				serverTime.getServiceTime().then(serverTime => {
					this.$set(this.ruleForm, "deliveryDate", serverTime.Format("yyyy-MM-dd"))
				})
			} else {
				this.$set(this.ruleForm, "deliveryDate", rowData[0].sendDate)
			}
			//创建送货单时处理明细行
			this.rowData = rowData
			this.rowData.forEach(row => {
				// 如是计划单传入计划单
				if (row.deliveryNo) {
					this.$set(row, "planNo", row.deliveryNo)
					this.$set(row, "planMxNo", row.deliveryIMxNo)
				}
			})
			if (this.rowData[0].area) this.ruleForm.area = this.rowData[0].area
			let hideCol = this.rowData.every(row => {
				// 判断明细中所有价格单位与单位是否一致
				return row.unitCode == row.priceUnit
			})
			if (hideCol) {
				this.$refs.agGirdComponent.gridOptions.columnApi.setColumnVisible(
					"priceUnit",
					false
				);
				this.$refs.agGirdComponent.gridOptions.columnApi.setColumnVisible(
					"priceAmount",
					false
				);
			}
			if (!this.rowData[0].planNo) {
				this.$refs.agGirdComponent.gridOptions.columnApi.setColumnVisible(
					"planNo",
					false
				);
				this.$refs.agGirdComponent.gridOptions.columnApi.setColumnVisible(
					"planMxNo",
					false
				);
			}
			this.$refs.agGirdComponent.gridOptions.api.setRowData(this.rowData);
			this.getDeliveryNo()
			this.$refs.agGirdComponent.gridOptions.api.forEachNode((node) => {
				//新增时id 默认为0
				node.data.id = 0
				if (!this.deliveryState) node.data.actualAmount = 0
				if (!node.data.priceAmount) node.data.priceAmount = 0
				if (!node.data.scanAmount) node.data.scanAmount = 0
				//送货数量默认设置为可发数量 //jjc20190324注释 begin
				// if (node.data.deliveryNum > 0&&node.data.isBarCode==0)
				//   {
				if (node.data.deliveryNum) node.data.actualAmount = node.data.deliveryNum
				if (node.data.beSentNum) node.data.actualAmount = node.data.beSentNum
				if (node.data.planAmount) node.data.planConAmount = node.data.planAmount
				//   } else {
				//     node.data.actualAmount = 0;

				//   }
				//jjc20190324注释 end
				let rowIndex = this.$refs.agGirdComponent.gridOptions.api.getRowNode(node.rowIndex)
				//设置行号
				rowIndex.setDataValue("deliveryIMxNo", node.rowIndex + 1)
				// rowIndex.setDataValue("actualAmount", 0);
				//设置底部合计
				if (node.data.actualAmount != null) {
					this.totalPlanAmount = addOperation.accAdd(
						node.data.actualAmount,
						this.totalPlanAmount
					)
					this.$refs.agGirdComponent.gridOptions.api.setPinnedBottomRowData(
						this.createBottomRow(1, "Bottom")
					)
				}
			})
			this.$refs.agGirdComponent.rowDataChange = true
		},
		closeBook () {
			this.showBookTimeDialog = false;
		},
		getBookTimeForm (bookForm) {
			this.showBookTimeDialog = false;
			this.appointmentEntity = bookForm;
			this.audit();
		}
	},
	beforeMount () {
		this.gridOptions = {
			context: {
				componentParent: this
			},
			//	            enableColResize: true,
			//	            localeText: localeText,
			//          	defaultColDef:{
			//      	    	menuTabs:[]
			//      	    },
			//          	getContextMenuItems:[],
			// onCellKeyDown: this.cellValueChanged,
			singleClickEdit: true,
			onCellFocused: this.cellFocused,
			onCellEditingStarted: this.cellEditingStarted,
			//   onGridReady: this.girdReady,
			pinnedBottomRowData: this.createBottomRow(1, "Bottom"),
			getRowStyle: function (params) {
				if (params.node.rowPinned) {
					return { color: "red", "font-weight": "bold" };
				}
			}
		};
		this.columnDefs = [
			{
				headerName: "操作",
				field: "operator",
				cellRendererFramework: operator,
				width: 50,
				hide: this.isHide
			},
			{
				headerName: "行号",
				field: "deliveryIMxNo",
				width: 50,
				// cellRenderer: function(params) {
				// //   if (params.node.id != null)
				// //   	return parseInt(params.node.id) + 1;
				// }
			},
			{ headerName: "物料编码", field: "matCode", width: 100 },
			{ headerName: "物料描述", field: "matName", width: 200 },
			//jjc
			{ headerName: "订单数量", field: "orderAmount", width: 80 },
			{
				headerName: "送货数量",
				field: "actualAmount",
				editable: true,
				cellEditorFramework: NumericEditorComponent,
				width: 80,
				onCellValueChanged: this.cellValueChanged
			},
			{ headerName: "单位", field: "unitCode", width: 60 },
			//			{	headerName:"销售数量",field:"priceAmount"},
			//			{	headerName:"单位",field:"priceUnit"},
			// {
			//   headerName: "计划送货数量",
			//   field: "planAmount",
			//   editable: true,
			//   cellEditorFramework: NumericEditorComponent, 
			//   width:80
			// },

			{
				headerName: "价格数量",
				field: "priceAmount",
				editable: true,
				cellEditorFramework: NumericEditorComponent,
				width: 80
				// cellStyle:function(params){
				//     if (!params.node.rowPinned) {
				//         return { 'background-color': "#fff" }
				//     }
				// },
			},
			{
				headerName: "价格单位",
				field: "priceUnit",
				width: 80
			},
			{ headerName: "采购订单", field: "purOrdNo", width: 100 },
			{ headerName: "采购订单行号", field: "purOrdMxNo", width: 120 },
			{ headerName: "备注", field: "remark", editable: true, width: 110 },
			{
				headerName: "防伪",
				field: "isBarCode",
				editable: false,
				width: 80,
				cellRenderer: function (params) {
					if (params.value === 1)
						return '<span class="ag-icon ag-icon-checkbox-checked" ></span>'
					else
						return '<span class="ag-icon ag-icon-checkbox-unchecked" ></span>'
				}
			},
			{ headerName: "扫码数量", field: "scanAmount", editable: false, width: 80, cellRenderer: buttonLink },
			{ headerName: "计划单号", field: "planNo", width: 140 },
			{ headerName: "计划单行号", field: "planMxNo", width: 120 },
		];
		let planAmountCol = {
			headerName: "计划数量",
			field: "planConAmount",
			width: 80
		}
		if (this.$global.isTransport) this.columnDefs.splice(4, 1, planAmountCol)
		// 扫码信息弹窗表格列信息
		this.barCodeColumnDefs = [
			//   { headerName: "送货单号", field: "deliveryNo"},
			{
				headerName: "生成日期",
				field: "createDate",
				cellRenderer: function (params) {
					if (params.value)
						return new Date(Date.parse(params.value.replace(/-/g, "/"))).Format("yyyy-MM-dd");
				}
			},
			{
				headerName: "生产日期",
				field: "produceDate",
				cellRenderer: function (params) {
					if (params.value)
						return new Date(Date.parse(params.value.replace(/-/g, "/"))).Format("yyyy-MM-dd");
				}
			},
			{
				headerName: "条码",
				field: "",
				cellRenderer: function (params) {
					var hideStr = params.data.barcode.substring(4, params.data.barcode.length - 4);
					return params.data.barcode.replace(hideStr, '**********');
				}
			}
		]
	},
	mounted () {
		this.$set(operator, "delDetailsShow", true);
		var that = this;
		this.$refs.agGirdComponent.gridOptions.api.setFocusedCell("actualAmount")
		//初始化公司数据源
		authInfo.getAuthInfo().then(authCompanyInfo => {
			that.comOptions = authCompanyInfo;
		});
		//
		if (this.pageLayOut == "add") {
			this.totalPlanAmount = 0;
			// this.btnShow = true;
			this.inputDis = true;
			if (this.$global.user.userTypeId == 4) {
				this.ruleForm.supplierId = this.supplierInfo[0].id;
				this.ruleForm.supplierCode = this.supplierInfo[0].supplierCode;
				this.ruleForm.supplierName = this.supplierInfo[0].supplierName;
				if (this.isTransport) {
					let transport = this.$global.transport
					this.ruleForm.transportID = transport.id
					this.ruleForm.transportName = transport.transportName
				}
			}
			//设置送货单号
			//   this.getDeliveryNo();
		}
		else if (this.pageLayOut == "edit") {
			this.inputDis = true;
			this.inputDis2 = false;
			//jjc20190223  
			this.ruleForm = JSON.parse(JSON.stringify(this.getClickValue));
			if (
				this.getClickValue.billState === 1 ||
				this.getClickValue.billState === 2
			)
				this.btnShow = true;
			else {
				this.btnShow = false;
				this.dropButShow = true;
			}
			if (this.getClickValue.billState === 3) {
				this.remarkDis = true;
				// this.offset = 22;
				//已审核的时候，偏移多一个按钮位置
				this.offset = 20;
				this.$refs.agGirdComponent.gridOptions.columnApi.setColumnVisible(
					"operator",
					false
				);
			} else this.remarkDis = false;

			//如果是送货看板跳转的明细，所有编辑状态取消
			if (this.getClickValue.indexSign == 'deliveryReport') {
				this.btnShow = false;
				this.dropButShow = false;
				this.inputDis = true;
				this.remarkDis = true;
				this.isHide = true;
				this.offset = 22;
				this.$refs.agGirdComponent.gridOptions.columnApi.setColumnVisible(
					"operator",
					false
				);

				this.displayDeliverybillDetail(this.getClickValue.deliveryID);
			} else {
				this.displayDeliverybillDetail(this.getClickValue.id);
			}
		}
	},
	components: {
		agGridComponents, bookDialog
	},
	props: ["getClickValue", "pageLayOut", "supplierInfo", "companyInfo", "deliveryState", "barCodes", "addTab"]
};
</script>

<style lang="less">
/*.redItem .el-form-item__label{
        color: red;
	}*/
.isBook {
	.el-input-group__prepend {
		width: 100%;
	}
	& > input {
		width: 0px;
		padding: 0 !important;
	}
}
</style>